<template>
  <view class="account-flow-container">
    <!-- 导航栏 -->
    <nav-bar></nav-bar>
    <!-- 收支统计 -->
    <view class="statistics-card">
      <view class="stat-item">
        <text class="label">本月收入</text>
        <text class="amount income">+{{ monthlyIncome }}</text>
      </view>
      <view class="divider"></view>
      <view class="stat-item">
        <text class="label">本月支出</text>
        <text class="amount expense">-{{ monthlyExpense }}</text>
      </view>
    </view>
    
    <!-- 流水列表 -->
    <scroll-view class="flow-list" scroll-y @scrolltolower="loadMore">
      <!-- 日期分组 -->
      <block v-for="(group, date) in groupedFlows" :key="date">
        <!-- 日期标题 -->
        <view class="date-header">
          <text class="date">{{ formatDate(date) }}</text>
          <text class="summary">收入 {{ group.income }} / 支出 {{ group.expense }}</text>
        </view>
        
        <!-- 流水项目 -->
        <view class="flow-item" v-for="(flow, index) in group.items" :key="index">
          <view class="flow-info">
            <view class="main-info">
              <text class="type">{{ flow.typeName }}</text>
              <text class="time">{{ flow.createTime }}</text>
            </view>
            <view class="sub-info">
              <text class="order-no">订单号：{{ flow.orderNo }}</text>
              <text class="remark" v-if="flow.remark">{{ flow.remark }}</text>
            </view>
          </view>
          <view class="amount-info" :class="flow.type">
            <text class="prefix">{{ flow.type === 'income' ? '+' : '-' }}</text>
            <text class="amount">{{ flow.amount }}</text>
          </view>
        </view>
      </block>
      
      <!-- 加载更多 -->
      <view class="loading-more" v-if="hasMore">
        <text>加载中...</text>
      </view>
      
      <!-- 无数据提示 -->
      <view class="empty-tip" v-if="Object.keys(groupedFlows).length === 0">
        <image src="/static/empty.png" mode="aspectFit" class="empty-icon"></image>
        <text>暂无账户流水</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import TechNavBar from '@/components/tech-nav-bar.vue'
import NavBar from '@/components/nav-bar/nav-bar.vue'

export default {
  components: {
    TechNavBar,
    NavBar
  },
  
  data() {
    return {
      monthlyIncome: '0.00',
      monthlyExpense: '0.00',
      page: 1,
      pageSize: 20,
      hasMore: true,
      groupedFlows: {},
      techId: ''
    }
  },
  
  onLoad() {
    this.getTechId()
    this.loadAccountFlow()
  },
  
  methods: {
    // 获取技师ID
    getTechId() {
      const userInfo = uni.getStorageSync('userInfo')
      this.techId = userInfo ? userInfo.techId || '' : ''
      console.log('技师ID:', this.techId)
    },
    
    // 加载账户流水
    async loadAccountFlow() {
      if (!this.techId) {
        console.error('技师ID不存在')
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      
      if (!this.hasMore) return
      
      uni.showLoading({
        title: '加载中...'
      })
      
      try {
        const token = uni.getStorageSync('token')
        
        const res = await new Promise((resolve, reject) => {
          uni.request({
            url: `${uni.$config.baseUrl}/accountFlow/accountFlow/listAll`,
            method: 'GET',
            header: {
              'Authorization': 'Bearer ' + token,
              'Content-Type': 'application/json'
            },
            data: {
              technicianId: this.techId
            },
            success: (response) => {
              resolve(response);
            },
            fail: (error) => {
              reject(error);
            }
          });
        })
        
        console.log('API响应:', res)
        const response = res.data
        
        if (response.code === 200) {
          const newFlows = response.rows || []
          this.hasMore = newFlows.length === this.pageSize
          
          // 处理并分组数据
          newFlows.forEach(flow => {
            // 从create_time中提取日期部分
            const date = flow.createTime.split(' ')[0]
            const time = flow.createTime.split(' ')[1].substring(0, 8)
            
            if (!this.groupedFlows[date]) {
              this.groupedFlows[date] = {
                income: '0.00',
                expense: '0.00',
                items: []
              }
            }
            
            // 转换数据格式
            const formattedFlow = {
              typeName: flow.type_name,
              type: flow.type === 1 ? 'income' : 'expense',
              amount: parseFloat(flow.amount).toFixed(2),
              orderNo: flow.order_no || '无',
              createTime: time,
              remark: flow.remark || ''
            }
            
            // 更新日期组的收支统计
            if (flow.type === 1) {
              this.groupedFlows[date].income = (
                parseFloat(this.groupedFlows[date].income) +
                parseFloat(formattedFlow.amount)
              ).toFixed(2)
            } else {
              this.groupedFlows[date].expense = (
                parseFloat(this.groupedFlows[date].expense) +
                parseFloat(formattedFlow.amount)
              ).toFixed(2)
            }
            
            this.groupedFlows[date].items.push(formattedFlow)
          })
          
          this.page++
          
          // 计算月度统计
          this.calculateMonthlyStats()
        } else {
          throw new Error(response.msg || '获取流水失败')
        }
      } catch (err) {
        console.error('获取账户流水失败:', err)
        console.log('错误详情:', JSON.stringify(err))
        uni.showToast({
          title: err.message || '获取流水失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 计算月度统计
    calculateMonthlyStats() {
      let income = 0
      let expense = 0
      
      Object.values(this.groupedFlows).forEach(group => {
        income += parseFloat(group.income)
        expense += parseFloat(group.expense)
      })
      
      this.monthlyIncome = income.toFixed(2)
      this.monthlyExpense = expense.toFixed(2)
    },
    
    // 格式化日期
    formatDate(dateStr) {
      const date = new Date(dateStr)
      const today = new Date()
      const yesterday = new Date(today)
      yesterday.setDate(yesterday.getDate() - 1)
      
      if (dateStr === today.toISOString().split('T')[0]) {
        return '今天'
      } else if (dateStr === yesterday.toISOString().split('T')[0]) {
        return '昨天'
      } else {
        return dateStr
      }
    },
    
    // 加载更多
    loadMore() {
      if (this.hasMore) {
        this.loadAccountFlow()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.account-flow-container {
  min-height: 100vh;
  background: #F5F5F5;
  padding-bottom: 30rpx;
  
  .statistics-card {
    margin: 30rpx;
    background: #FFFFFF;
    border-radius: 20rpx;
    padding: 40rpx 30rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
    box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.05);
    
    .stat-item {
      flex: 1;
      text-align: center;
      
      .label {
        font-size: 32rpx;
        color: #666666;
        margin-bottom: 16rpx;
        display: block;
        font-weight: 500;
      }
      
      .amount {
        font-size: 44rpx;
        font-weight: bold;
        
        &.income {
          color: #07C160;
        }
        
        &.expense {
          color: #FF4D4F;
        }
      }
    }
    
    .divider {
      width: 2rpx;
      height: 100rpx;
      background: #EEEEEE;
    }
  }
  
  .flow-list {
    padding: 0 30rpx;
    
    .date-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx 10rpx 20rpx;
      
      .date {
        font-size: 32rpx;
        color: #333333;
        font-weight: 600;
      }
      
      .summary {
        font-size: 28rpx;
        color: #666666;
      }
    }
    
    .flow-item {
      background: #FFFFFF;
      border-radius: 16rpx;
      padding: 30rpx;
      margin-bottom: 24rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
      
      .flow-info {
        flex: 1;
        margin-right: 20rpx;
        
        .main-info {
          margin-bottom: 16rpx;
          
          .type {
            font-size: 34rpx;
            color: #333333;
            margin-right: 20rpx;
            font-weight: 500;
          }
          
          .time {
            font-size: 28rpx;
            color: #999999;
          }
        }
        
        .sub-info {
          font-size: 28rpx;
          color: #999999;
          
          .order-no {
            margin-right: 20rpx;
          }
        }
      }
      
      .amount-info {
        text-align: right;
        
        &.income {
          color: #07C160;
        }
        
        &.expense {
          color: #FF4D4F;
        }
        
        .prefix {
          font-size: 32rpx;
        }
        
        .amount {
          font-size: 40rpx;
          font-weight: bold;
        }
      }
    }
    
    .loading-more {
      text-align: center;
      padding: 30rpx 0;
      color: #999999;
      font-size: 28rpx;
    }
    
    .empty-tip {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 150rpx 0;
      
      .empty-icon {
        width: 240rpx;
        height: 240rpx;
        margin-bottom: 30rpx;
      }
      
      text {
        font-size: 32rpx;
        color: #999999;
      }
    }
  }
}
</style> 